package com.gmrz.uap.facet;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.dict.DictConst;
import com.gmrz.uap.dict.DictService;
import com.gmrz.uap.model.Facets;
import com.gmrz.uap.operlog.OperLogService;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.util.ApkFacetIDUtil;
import com.gmrz.uap.util.Identities;
import com.gmrz.uap.util.ZipUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.ExceededSizeException;
import com.jfinal.upload.UploadFile;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.exceptions.JedisConnectionException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FacetController extends ControllerSupport {

    private static final Logger LOG = LoggerFactory.getLogger(FacetController.class);

    /**
     * 应用管理主页面
     */
    @Before(ResourceInterceptor.class)
    public void index() {
    }

    /**
     * 根据前台发过来的参数进行分页,查询
     */
    public void list() {

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, SystemConst.DEFAULT_ORDERBY_CREATETS);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Facets facets = getModel(Facets.class);

        Page<Facets> pages = FacetService.me.findListPaginate(facets, page, rows, sort, order, getCookie(SystemConst.COOKIE_TENANT_ID));

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, pages.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, pages.getList());

        render(responseJsonRender(result));
    }

    /**
     * 下载facets.uaf文件
     */
    public void downloadFacetFile() {
        HttpServletResponse response = getResponse();
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=facets.uaf");
        makeDownload(response, getCookie(SystemConst.COOKIE_TENANT_ID));
        renderNull();
    }

    /**
     * 增加页面跳转
     */
    public void add() {

        setAttr("dictList", DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_APP_TYPE_ID));
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 添加应用
     */
    public void save() {

        Facets facets = getModel(Facets.class);

        if (null == facets) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        flag = FacetService.me.exist(facets.getFacetName(), tenantId);
        if (!flag) {
            message = "应用信息已经存在";
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        try {

            facets.setFacetId(Identities.uuid2());
            facets.setTenantId(tenantId);
            flag = facets.save();

            if (flag) {
                message = getRes().get("system.validator.add.success");
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.UAFFACETID, message);
            } else {
                message = getRes().get("system.validator.add.cache.failure");
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("添加FACET_ID", facets.getFacetName(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void edit() {
        setAttr("facets", FacetService.me.findById(getPara()));
        setAttr("dictList", DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_APP_TYPE_ID));
        render("form" + SystemConst.VIEW_EXTENDSION);
    }



    public void update() {
        Facets facets = getModel(Facets.class);

        if (null == facets) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);

        try {

            facets.setTenantId(tenantId);
            flag = facets.update();

            if (flag) {
                message = "编辑应用成功！";
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.UAFFACETID, message);
            } else {
                message = getRes().get("system.validator.add.cache.failure");
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }


        //增加系统操作日志
        OperLogService.me.addOperLog("编辑应用", facets.getFacetName(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));

    }

    /**
     * 删除应用
     */
    public void remove() {

        String ids = getPara(0);
        String facetName = "";

        String[] isArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);

        if (isArr.length >= 1) {
            for (String id : isArr) {
                Facets byId = FacetService.me.findById(id);
                facetName += byId.getFacetName() + SystemConst._DEFAULT_SEPARATOR_COMMA;
            }
        }

        if (StrKit.isBlank(ids)) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        try {

            flag = FacetService.me.remove(ids, getCookie(SystemConst.COOKIE_TENANT_ID));

            if (flag) {
                message = getRes().get("system.validator.remove.success");
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.UAFFACETID, message);
            } else {
                message = getRes().get("system.validator.remove.error");
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("删除FACET_ID", facetName, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 流下载
     *
     * @param response
     */
    private void makeDownload(HttpServletResponse response, String tanentid) {
        BufferedReader bfr = null;
        BufferedWriter bfw = null;
        try {
            bfr = FacetService.me.getFacetsFileStream(tanentid);
            bfw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
            String len = null;
            while ((len = bfr.readLine()) != null) {
                bfw.write(len);
                bfw.newLine();
            }
        } catch (IOException e) {
        } finally {
            if (bfr != null)
                try {
                    bfr.close();
                } catch (IOException e) {
                }
            if (bfw != null)
                try {
                    bfw.close();
                } catch (IOException e) {
                }
        }
    }


    public void generateFacetId() {
    }


    public void getFacetIdFromApk() {
        int uploadFileSize = PropKit.use("application.properties").getInt("upload.file.size");
        String filePath = Identities.uuid2();

        try {
            UploadFile uploadFile = getFile("apkFile", filePath, uploadFileSize * 1024 * 1024);
            String filename = uploadFile.getFileName();
            filePath = uploadFile.getUploadPath();

            if (!filename.toLowerCase().endsWith(".apk")) {//如果文件格式不是APK

                FileUtils.deleteDirectory(new File(filePath));

                result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
                result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "文件格式不正确，请重新选择");
                render(responseJsonRender(result));
                return;
            }


            String apkNewFilePath = filePath + "/" + filename;
            ZipUtil.unzip(apkNewFilePath);
            String metaDirectoryPath = filePath + "/META-INF/";

            File metaDirectoryFile = new File(metaDirectoryPath);
            File[] metaFileList = metaDirectoryFile.listFiles();

            //在文件夹中查找RSA文件
            String certPath = null;
            for (File tmpFile : metaFileList) {
                boolean flag = tmpFile.getName().toString().toLowerCase().contains(".rsa");
                if (flag) {
                    certPath = metaDirectoryPath + tmpFile.getName();
                    break;
                }
            }

            if (StrKit.isBlank(certPath)) {//如果没找到文件
                throw new RuntimeException();
            }


            message = ApkFacetIDUtil.exec(certPath);
            flag = true;

            FileUtils.deleteDirectory(new File(filePath));

            OperLogService.me.addOperLog("生成FACET_ID", message, flag, message, getRequest());

        } catch (ExceededSizeException exceededSizeException) {
            message = "上传文件大小超过系统限制" + String.valueOf(uploadFileSize) + "M";
            LOG.error(message, exceededSizeException);
        } catch (IOException ioException) {
            LOG.error("删除目录出现异常", ioException);
        } catch (RuntimeException runtimeException) {
            message = "APK文件解析现异常，请检查文件是否正确";
            LOG.error(message, runtimeException);
        }

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

}
